package com.idbk.chargestation.app;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.util.Locale;

/**
 * 缓存管理器
 * @author lupc
 *
 */
public class ManagerCache {

	private final static String CACHE_MAP = "map";


	/**
	 * 判断SD卡是否挂载
	 */
	public static boolean isSDCARDMounted(){
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * 返回离线地图的路径
	 * @param context Context
	 */
	public static String getOfflineMapCacheDir(Context context){
		File dir = new File(context.getExternalFilesDir(null),CACHE_MAP);
		if (!dir.exists()) {
			dir.mkdir();
		}
		return dir.toString() + "/";
	}

	/**
	 * 返回缓存大小
	 * @param context Context
	 * @return 单位m
	 */
	public static String getCacheSize(Context context){
		File dir = context.getExternalCacheDir();
		long space = getDirSize(dir);
		return String.format(Locale.CHINA,"%.2f", space/1000d/1000d);
	}

	private static long getDirSize(File dir){
		long size = 0;
		for (File file : dir.listFiles()) {
			if (file != null && file.isDirectory()) {
				size += getDirSize(file);
			} else if (file != null && file.isFile()) {
				size += file.length();
			}
		}
		return size;
	}

	/**
	 * 清理缓存
	 * @param context Context
	 */
	public static void cleanCache(final Context context){
		File dir = context.getExternalCacheDir();
		deleteDir(dir);			
	}

	private static void deleteDir(File dir){
		for (File file : dir.listFiles()) {
			if (file != null && file.isDirectory()) {
				deleteDir(file);
			} else if (file != null && file.isFile()) {
				file.delete();
			}
		}
	}

}
